package com.yeren.servlet.tarena.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AddEmpServlet extends HttpServlet {
	/*
	 * 使用请求中的name,contact两组参数值 分别使用getParameter和getParameterValues方法获取
	 */
	public void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// 设置中文的输入和输出
		req.setCharacterEncoding("UTF-8");
		// 保证正确输出中文
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		// 获取提交的name的值
		String name = req.getParameter("name");
		double salary = Double.valueOf(req.getParameter("salary"));
		int age = Integer.valueOf(req.getParameter("age"));
		// 将数据插入到数据库liu_temp中
		Connection conn = null;
		PreparedStatement stat = null;
		try {
			Class.forName("oracle.jdbc.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott", "tiger");
			stat = conn.prepareStatement("insert into liu_temp values (emp_id_seq.nextval,?,?,?)");
			stat.setString(1, name);
			stat.setDouble(2, salary);
			stat.setInt(3, age);
			stat.executeUpdate();
			out.println("添加成功");
			resp.sendRedirect("list.do");//重定向
		} catch (Exception e) {
			e.printStackTrace();
			out.print("系统繁忙，稍后重试");
		} finally {         
			if (stat != null) {
				try {
					stat.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		/*不用数据库显示*/
//		out.print("<h1>员工信息</h1>");
//		out.print("<h1>员工姓名:"+name+"</h1>");
//		out.print("<h1>薪水:"+salary+"</h1>");
//		out.print("<h1>年龄:"+age+"</h1>");
//		out.close();
	}
}
